package server

import (
	"errors"
	"gorm.io/gorm"
	"me/123/common/dao/mysql"
	"me/123/common/model"
	"me/123/common/pkg"
	"me/123/common/proto/user"
)

func Login(req *user.LoginRequest) (*user.LoginResponse, error) {
	info, err := mysql.QueryUserInfo(req.Mobile)
	if err != nil {
		return nil, err
	}
	if info.Password != req.Password {
		return nil, errors.New("密码错误")
	}
	claims := pkg.CustomClaims{ID: uint(info.Id)}
	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		return nil, err
	}
	return &user.LoginResponse{Success: token}, nil
}

func CollectVoucher(req *user.CollectVoucherRequest) (*user.CollectVoucherResponse, error) {
	coupons, err := mysql.QueryCoupons(req.CouponsId)
	if err != nil {
		return nil, err
	}

	if coupons.ID == 0 {
		return nil, errors.New("没有该优惠卷")
	}

	info, err := mysql.QueryUserCouponsInfo(req.UserId, req.CouponsId)
	if err != nil {
		return nil, err
	}

	if info.Uid == int(req.UserId) && info.CouponsId == int(req.CouponsId) {
		return nil, errors.New("你已经领取过了")
	}

	uc := model.UserCoupons{
		Model:         gorm.Model{},
		Uid:           int(req.UserId),
		CouponsId:     int(req.CouponsId),
		CouponsName:   coupons.CouponsName,
		CouponPrice:   coupons.CouponPrice,
		UseMinPrice:   coupons.UseMinPrice,
		CouponsStatus: 2,
	}
	err = mysql.AddUserCoupons(&uc)
	if err != nil {
		return nil, err
	}
	return &user.CollectVoucherResponse{Success: "领取成功"}, nil
}
